<template>
  <div class="global-box">
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <a-row class="addtem" :gutter="60">
        <a-col :span="10">
          <h5>退费/重修条款</h5>
          <div class="model">
            <div class="modelContent">
              <div v-for="(item, index) in clauseTem" :key="index">
                <p class="termTitle" v-if="item.content && item.content.length !== 0">
                  {{ item.title }}
                </p>
                <p
                  class="termTitle"
                  v-if="
                    index === 0 &&
                    (item.sub[0].content.length !== 0 ||
                      item.sub[1].content.length !== 0 ||
                      item.sub[2].content.length !== 0)
                  "
                >
                  {{ item.title }}
                </p>
                <div v-if="item.sub">
                  <div v-for="(el, i) in item.sub" :key="i">
                    <p class="subtitle" v-if="el.content.length !== 0">{{ el.title }}</p>
                    <p class="text" v-for="(child, k) in el.content" :key="k">
                      {{ child }}
                      <a-icon type="close-circle" class="icon" @click="closeText" />
                    </p>
                  </div>
                </div>
                <div v-if="index !== 0">
                  <div v-for="(itemA, k) in item.content" :key="k">
                    <p class="text" v-if="item.content.length !== 0">
                      {{ itemA }}
                      <a-icon type="close-circle" class="icon" @click="closeText" />
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="model modelno" v-if="false">
            <div>
              <span>请添加退费/重修条款</span>
            </div>
          </div>
        </a-col>
        <a-col :span="12">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="基础信息">
              <a-form-model
                ref="addtemForm"
                :model="addtemForm"
                :rules="addtemFormRules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
              >
                <a-form-model-item label="协议模板名称" prop="name">
                  <a-input v-model="addtemForm.name" placeholder="请输入协议条款名称" />
                </a-form-model-item>
                <a-form-model-item label="课程目录" prop="directory">
                  <a-cascader
                    :field-names="{ label: 'value', value: 'id', children: 'children' }"
                    :options="directoryOptions"
                    :load-data="loadData"
                    placeholder="请选择课程目录"
                    change-on-select
                    v-model="addtemForm.directory"
                  />
                </a-form-model-item>
                <a-form-model-item label="协议模板类型" prop="type">
                  <a-radio-group v-model="addtemForm.type">
                    <a-radio :value="item.value" :key="item.value" v-for="item in typeList">{{
                      item.label
                    }}</a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <a-form-model-item label="所属事业部" prop="shiYeBu">
                  <a-select v-model="addtemForm.shiYeBu" placeholder="请选择所属事业部">
                    <a-select-option
                      :value="item.jiGouTableId"
                      :key="item.jiGouTableId"
                      v-for="item in affiliationList"
                    >
                      {{ item.jiGouName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="启用状态" prop="status">
                  <a-radio-group v-model="addtemForm.status">
                    <a-radio :value="item.value" :key="item.value" v-for="item in statusList">{{
                      item.label
                    }}</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-form-model>
            </a-tab-pane>
            <a-tab-pane key="2" tab="基础条款">
              <div class="form-wrapper">
                <a-form :form="addtemForm" :labelCol="{ span: 4 }" :wrapperCol="{ span: 8 }">
                  <a-form-item label="通用条款名称">
                    <a-select
                      v-model="addtemForm.terms"
                      placeholder="请选择通用条款名称"
                      @change="changeClauseList"
                    >
                      <a-select-option :value="item.id" :key="item.id" v-for="item in termsList">
                        {{ item.clauseName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-form>
                <div class="termsCont">
                  <h6>通用条款内容：</h6>
                  <p v-for="item in termsContent" :key="item.id">
                    {{ item.clauseContent }}
                  </p>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="3" tab="退费/重修条款">
              <div class="form-wrapper">
                <a-form layout="inline" :form="addtemForm">
                  <a-row :gutter="20">
                    <a-col :md="10" :sm="24">
                      <a-form-model-item label="协议条款ID" prop="name">
                        <a-input v-model="addtemForm.id" placeholder="请输入协议条款ID" />
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="10" :sm="24">
                      <a-form-model-item label="协议条款类型" prop="shiYeBu">
                        <a-select v-model="addtemForm.agreeType" placeholder="请选择协议条款类型">
                          <a-select-option
                            :value="item.value"
                            :key="item.value"
                            v-for="item in agreeTypeList"
                            >{{ item.label }}</a-select-option
                          >
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col :md="4" :sm="24">
                      <a-form-model-item>
                        <a-button type="primary" @click="search">筛选</a-button>
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-form>
                <div class="agreeList">
                  <ul>
                    <li v-for="item in clauseList" :key="item.id">
                      <div>
                        <span>{{ item.clauseName }}</span>
                        <a-button @click="addText(item)"> {{ item.text }} </a-button>
                      </div>
                      <p>{{ item.clauseContent }}</p>
                    </li>
                  </ul>
                </div>
                <a-pagination
                  show-quick-jumper
                  :total="page.totals"
                  :defaultCurrent="page.defaultCurrent"
                  :defaultPageSize="page.defaultPageSize"
                  @change="onChange"
                  @showSizeChange="onShowSizeChange"
                />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-col>
      </a-row>
      <div class="btn">
        <a-button @click="preview">预览</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </a-card>
    <drawer :drawer="addDrawer" @closeBox="closeBox" />
  </div>
</template>
<script>
import Drawer from './agreeDrawer'
import { directory, affiliation, getClause, clauseList, add, edit } from '@/api/agreement/template'
export default {
  components: {
    Drawer
  },
  data () {
    return {
      directoryOptions: [],
      addtemForm: {
        name: '',
        directory: [],
        type: 1,
        shiYeBu: undefined,
        text: '',
        status: 1,
        terms: undefined,
        id: '',
        agreeType: undefined
      },
      statusList: [
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 0
        }
      ],
      typeList: [{
        label: '通用',
        value: 1
      }, {
        label: '退费',
        value: 2
      }, {
        label: '重修',
        value: 3
      }, {
        label: '退费和重修',
        value: 4
      }],
      agreeTypeList: [{
        label: '完课比例',
        value: 2
      }, {
        label: '考试成绩',
        value: 3
      }, {
        label: '退费/重修其他要求',
        value: 4
      }, {
        label: '退费/重修申请期限',
        value: 5
      }, {
        label: '退费标准',
        value: 6
      }, {
        label: '重修年份',
        value: 7
      }, {
        label: '退费/重新申请材料',
        value: 8
      }],
      termsList: [],
      termsContent: [],
      affiliationList: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
      addtemFormRules: {
        name: [
          { required: true, message: '请输入协议条款名称', trigger: 'blur' }
        ],
        directory: [{ required: true, message: '请选择课程目录', trigger: 'change' }],
        type: [{ required: true, message: '请选择协议模板类型', trigger: 'change' }],
        shiYeBu: [{ required: true, message: '请选择所属事业部', trigger: 'change' }],
        status: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
      },
      addDrawer: {
        visible: false,
        clause: this.clauseTem
      },
      page: {
        defaultCurrent: 1,
        defaultPageSize: 6,
        totals: 0
      },
      clauseList: [],
      clauseTem: [{
        title: '5.1 退费/重修条款',
        type: -1,
        sub: [{
          title: '5.1.1 完课比例',
          type: 2,
          content: []
        }, {
          title: '5.1.2 考试成绩',
          type: 3,
          content: []
        }, {
          title: '5.1.3 退费/重修其他要求',
          type: 4,
          content: []
        }],
        content: []
      }, {
        title: '5.2 退费/重修申请期限',
        type: 5,
        content: []
      }, {
        title: '5.3 退费标准',
        type: 6,
        content: []
      }, {
        title: '5.4 重修年份',
        type: 7,
        content: []
      }, {
        title: '5.5 退费/重修申请材料',
        type: 8,
        content: []
      }],
      editData: ''
    }
  },
  mounted () {
    this.getDirectory()
    this.getAffiliation()
    this.getClauseNameList()
    this.getClauseList()
    if (this.$route.params.re) {
      this.editData = this.$route.params.re
      this.getData()
    }
  },
  computed: {
  },
  methods: {
    // 编辑、复制数据回显
    getData () {
      console.log(this.editData.otherClause)
      this.addtemForm.name = this.editData.templateName
      this.addtemForm.directory[0] = this.editData.directoryId
      this.addtemForm.directory[1] = this.editData.examId
      this.addtemForm.type = this.editData.templateCategory
      this.addtemForm.shiYeBu = this.editData.deptId
      this.addtemForm.status = this.editData.enable
      this.clauseTem = this.editData.otherClause !== '' && JSON.parse(this.editData.otherClause) || []
    },
    onShowSizeChange: (current, pageSize) => {
      this.page.defaultCurrent = 1
      this.page.defaultPageSize = pageSize
      this.getClauseList()
    },
    // 改变每页数量时更新显示
    onChange: (current, size) => {
      this.page.defaultCurrent = current
      this.page.defaultPageSize = size
      this.getClauseList()
    },
    // 提交
    onSubmit () {
      this.$refs.addtemForm.validate(valid => {
        if (valid) {
          this.save()
        } else {
          return false
        }
      })
    },
    save () {
      const data = {
        creatorId: 0,
        creatorName: '',
        deptId: this.addtemForm.shiYeBu || 0,
        deptName: '',
        directoryId: this.addtemForm.directory[0] || 0,
        directoryName: '',
        enable: this.addtemForm.status,
        examId: this.addtemForm.directory[1] || 0,
        examName: '',
        generalClause: this.addtemForm.terms || 0,
        otherClause: JSON.stringify(this.clauseTem),
        templateCategory: this.addtemForm.type || 0,
        templateName: this.addtemForm.name
      }
      if (this.$route.params.edit) {
        edit(data).then(res => {
          if (res.code === '1') {
            this.$message.success(res.msg)
            this.$router.push({
              name: 'template'
            })
          } else {
            this.$message.success(res.msg)
          }
        }).catch(err => {
          this.$message.error(err.msg)
        })
        return false
      } else {
        add(data).then(res => {
          if (res.code === '1') {
            this.$message.success(res.msg)
            this.$router.push({
              name: 'template'
            })
          } else {
            this.$message.success(res.msg)
          }
        }).catch(err => {
          this.$message.error(err.msg)
        })
      }
    },
    // 条款添加
    addText (obj) {
      if (obj.clauseCategory === 1) {
        return false
      }
      if (obj.text === '添加') {
        this.clauseTem.forEach(item => {
          if (obj.clauseCategory < 5) {
            item.sub && item.sub.forEach(el => {
              if (el.type === obj.clauseCategory && !el.content.includes(obj.clauseContent)) {
                el.content.push(obj.clauseContent)
                obj.text = '取消添加'
              }
            })
          }
          if (item.type === obj.clauseCategory && !item.content.includes(obj.clauseContent)) {
            item.content.push(obj.clauseContent)
            obj.text = '取消添加'
          }
        })
      } else {
        this.clauseTem.forEach((item, index) => {
          if (obj.clauseCategory < 5) {
            item.sub && item.sub.forEach((el, i) => {
              if (el.type === obj.clauseCategory) {
                el.content.forEach((child, k) => {
                  el.content.splice(k, 1)
                })
                obj.text = '添加'
              }
            })
          }
          if (item.type === obj.clauseCategory) {
            item.content.splice(index, 1)
            obj.text = '添加'
          }
        })
        console.log(this.clauseTem)
      }
    },
    // 条款删除
    closeText () { },
    // 预览
    preview () {
      this.addDrawer.visible = true
      this.addDrawer.clause = this.clauseTem
    },
    closeBox (v) {
      this.addDrawer = {
        visible: false,
        clause: []
      }
    },
    // 获取通用条款名称
    getClauseNameList () {
      const data = {
        clauseCategory: 1,
        clauseName: '',
        id: this.addtemForm.terms || 0
      }
      getClause(data).then(res => {
        if (res.code === '1') {
          this.termsList = res.data
          this.addtemForm.terms = res.data[0].id
          this.changeClauseList()
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    changeClauseList () {
      const data = {
        clauseCategory: 1,
        clauseName: '',
        id: this.addtemForm.terms || 0
      }
      getClause(data).then(res => {
        if (res.code === '1') {
          this.termsContent = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 筛选
    search () {
      this.getClauseList()
    },
    // 退费重修条款
    getClauseList () {
      const data = {
        currentPage: this.page.defaultCurrent,
        pageSize: this.page.defaultPageSize,
        clauseId: this.addtemForm.id || 0,
        clauseCategory: this.addtemForm.agreeType || 0,
        enable: 1,
        clauseName: '',
        directoryId: 0,
        examId: 0
      }
      clauseList(data).then(res => {
        if (res.code === '1') {
          this.page.totals = res.data.totalSize
          this.clauseList = res.data.rows
          this.clauseList.forEach(item => {
            item.text = '添加'
          })
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取所属机构
    getAffiliation () {
      affiliation({}).then(res => {
        if (res.code === '1') {
          this.affiliationList = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      if (this.addtemForm.directory[1]) {
        return false
      }
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.addtem {
  margin-top: 40px;
  h5 {
    font-size: 18px;
    margin-bottom: 20px;
  }
  .label {
    a {
      padding-right: 10px;
    }
  }
  .modelno {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .model {
    padding: 15px 0;
    min-height: 650px;
    background: rgba(0, 0, 0, 0.04);
    .modelContent {
      p {
        padding: 0 15px;
        line-height: 24px;
      }
      .text {
        position: relative;
        .icon {
          display: none;
          position: absolute;
          top: 50%;
          right: -22px;
          font-size: 22px;
          margin-top: -11px;
          cursor: pointer;
        }
        &:hover {
          background: rgba(232, 232, 232, 1);
          .icon {
            display: block;
          }
        }
      }
    }
  }
  .termsCont {
    margin-left: 1%;
    h6 {
      font-size: 14px;
      margin-bottom: 20px;
    }
  }
  .agreeList {
    ul {
      width: 100%;
      padding-left: 0;
      li {
        border-bottom: 1px solid rgba(233, 233, 233, 1);
        margin-bottom: 10px;
        padding-bottom: 10px;
        padding-right: 3%;
        div {
          display: flex;
          justify-content: space-between;
        }
        p {
          margin-top: 10px;
        }
      }
    }
  }
}
.btn {
  text-align: center;
  margin-top: 30px;
  .ant-btn {
    margin: 0 15px;
  }
}
</style>
